package org.rico.commons.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

/**
 * springmvc 日期conversion-service
 * @author rico
 *
 */
public class DateConverter implements Converter<String, Date> {

    // Date formats are not synchronized. It is recommended to create separate format instances for each thread.
    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        }
    };
    private final static ThreadLocal<SimpleDateFormat> datetimeFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.SIMPLIFIED_CHINESE);
        }
    };

    @Override
    public Date convert(String date) {
        if (StringUtils.isBlank(date)) {
            return null;

        } else if (StringUtils.isNumeric(date)) {
            return new Date(Long.valueOf(date).longValue());

        } else {
            try {
                return datetimeFormater.get().parse(date);

            } catch (ParseException ex) {
                try {
                    return dateFormater.get().parse(date);

                } catch (ParseException e) {
                    e.printStackTrace();
                    //throw new BusinessException("日期格式不正确！");
                }
            }
        }

        return null;
    }

}
